package com.asset.salesforce.dao;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;


import com.asset.salesforce.domain.Employee;
import com.asset.salesforce.domain.User;

@Repository
public class UserShiroDaoImpl {
	
	private SessionFactory sessionFactory=null;
	
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public void editUser(User user){
		Session session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(user);
	}
	
	public void addUser(User user) {
		try{
		sessionFactory.getCurrentSession().save(user);
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public void deleteUser(User user) {
		try{
		sessionFactory.getCurrentSession().delete(user);
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public List<User> getAllUsers(Employee employee) {
		try{
			
		Query query =sessionFactory.getCurrentSession().createQuery("from User u Where u.companyId.company.id=:companyId");
		query.setParameter("companyId", employee.getCompany().getId());
		List<User> users = new ArrayList<User>();
		users = query.list();	
		System.out.println(">>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<"+query.list().size()+" "+employee.getCompany().getId());
		return  query.list();		
		}catch(Exception ex){
			ex.printStackTrace();
			return null;
		}
	}
	
	public User getUserById(Integer userId) {
        return (User) sessionFactory.getCurrentSession().load(User.class, userId);
    }
	
	public User findUser(String username) {
       
        String query = "from User u where u.username = :username";
        return (User) sessionFactory.getCurrentSession().createQuery(query).setString("username", username).uniqueResult();
    }

}
